//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by NeXTSTEP on 15/10/2.
//  Copyright © 2015年 NeXTSTEP. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


class OAuthViewController: BaseViewController,UIWebViewDelegate {

    private let WB_Client_Id = "315779718"
    private let WB_Redirect_Uri = "http://www.itcast.cn"
    private let WB_Client_Secret = "ed07732b25cde6a688c579b758898e7d"
    //属性webView 将根视图强转为view
    var webView: UIWebView {
        return view as! UIWebView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadAuthPage()
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    @IBAction func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @IBAction func defaultAccount(sender: AnyObject) {
        let jsString = "document.getElementById('userId').value = 'panxing@itcast.cn',document.getElementById('passwd').value = 'xing2580'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    private func loadAuthPage() {
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL)
        let urlString = request.URL!.absoluteString
        if urlString.hasPrefix("https://api.weibo.com/") {
            return true
        }
        if !urlString.hasPrefix(WB_Redirect_Uri) {
            return false
        }
        let query = request.URL!.query!
        let codeStr = "code="
        if query.hasPrefix(codeStr) {
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            print(code)
            loadUserInfo(code)
        }
        return false
    }
    
    func loadUserInfo(code: String){
        NetworkTools.sharedTools.loadAccessToken(code) { (dict, error) -> () in
            if dict == nil || error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                self.closeOAuthPage()
                return
            }
            
            let account = UserAccount(dict: dict!)
            account.loadUserInfo({ (error) -> () in
                if error != nil {
                    SVProgressHUD.showInfoWithStatus("您的网络不给力")
                    self.closeOAuthPage()
                    return
                }
                
                print("登录成功")
                self.close()
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchToRootVC, object: "WelCome")
            })
        }
    }
    
    private func closeOAuthPage(){
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) { () -> Void in
            self.close()
        }
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }


}
